package com.example.teacher.controller.front;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.commonutils.JwtUtils;
import com.example.commonutils.ResultData;
import com.example.servicebase.client.OrderClient;
import com.example.servicebase.client.UcenterClient;
import com.example.servicebase.client.VodClient;
import com.example.servicebase.exceptionhandler.CustomException;
import com.example.teacher.entity.*;
import com.example.teacher.entity.chapter.VideoVo;
import com.example.teacher.service.EduCommentService;
import com.example.teacher.service.EduCourseService;
import com.example.teacher.service.EduVideoService;
import com.example.teacher.service.HistoryService;
import com.example.teacher.utils.SnowflakeIdWorker;
import io.netty.util.internal.StringUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.MediaType;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/backstage/VideoFront")
public class VideoFrontController {

    @Autowired
    private VodClient vodClient;
    @Autowired
    private EduVideoService videoService;

    @Autowired
    private EduCourseService courseService;

    @Autowired
    private HistoryService historyService;

    @Autowired
    private OrderClient orderClient;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Qualifier("com.example.servicebase.client.UcenterClient")
    @Autowired
    private UcenterClient client;

//    private Integer viewCount=0;

    //获取小节视频播放页面信息
    @GetMapping(value = "getVideoInfo/{vid}",produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResultData getVideoInfo(@PathVariable String vid,HttpServletRequest request){
        //根据小结id查询小结
        EduVideo video = videoService.getById(vid);
        //根据查询到的小节信息拿到课程id
        String courseId = video.getCourseId();
        //根据课程id查询出所有的免费小节
        QueryWrapper<EduVideo> wrapper =new QueryWrapper<>();
        wrapper.eq("course_id",courseId);
        String token = JwtUtils.getMemberIdByJwtToken(request);
        //判断用户是否登录
        if (!StringUtil.isNullOrEmpty(token)) {
            //用户登录了，判断用户是否购买
            boolean buyCourse = orderClient.isBuyCourse(courseId, token);
            if (!buyCourse) {
                //用户未购买，查询免费小结
                wrapper.eq("is_free", 1);
            }
        }else{
            //用户未登录，查询免费小节
            wrapper.eq("is_free", 1);
        }
        List<EduVideo> videos = videoService.list(wrapper);
        List<VideoVo> list = new ArrayList<>();
        for (EduVideo v : videos) {
            VideoVo videoVo = new VideoVo();
            BeanUtils.copyProperties(v,videoVo);
            list.add(videoVo);
        }
//        String id = video.getVideoSourceId();
//        String playAuth = vodClient.getPlayAuth(id);
//        String videoSourceId = video.getVideoSourceId();

        return ResultData.ok().data("list",list);
//                .data("playAuth",playAuth)
//                .data("videoSourceId",videoSourceId);
    }

    @GetMapping("getVideoPlayAuth/{vid}")
    public ResultData getVideoPlayAuth(@PathVariable String vid,HttpServletRequest request){
        //根据小结id查询小结
        EduVideo video = videoService.getById(vid);
        String id = video.getVideoSourceId();
        String playAuth = vodClient.getPlayAuth(id);
        String videoSourceId = video.getVideoSourceId();
        return ResultData.ok()
                .data("playAuth",playAuth)
                .data("videoSourceId",videoSourceId);
    }

    //分页获取评论
    @GetMapping(value = "commentCount/{vid}/{limit}",produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResultData commentCount(@PathVariable("vid") String vid , @PathVariable("limit") int limit, HttpServletRequest request){
        //从请求中获取token
        String token = JwtUtils.getMemberIdByJwtToken(request);
        String memberId="";
        if (!StringUtil.isNullOrEmpty(token)){
            memberId = JwtUtils.getMemberIdByJwtToken(request);
        }
        //根据小结id查询
        EduVideo video = videoService.getById(vid);
        String courseId = video.getCourseId();
        //根据课程id去查询评论表
//        QueryWrapper<Comment> wrapper1 =new QueryWrapper<>();
        Query query =new Query(Criteria.where("courseId").is(courseId));
        query.with(Sort.by(
                Sort.Order.desc("gmtCreate")
        ));
        query.limit(limit);
//        wrapper1.eq("course_id",courseId).orderByDesc("gmt_create").last("limit "+limit);
        List<Comment> comments = mongoTemplate.find(query, Comment.class,"comment");
        /*List<EduComment> comments = commentService.list(wrapper1);
        QueryWrapper<EduComment> commentTotal =new QueryWrapper<>();
        commentTotal.eq("course_id",courseId);*/
        Query count =new Query(Criteria.where("courseId").is(courseId));
        long size = mongoTemplate.count(count,Comment.class,"comment");
        return ResultData.ok().data("comments",comments).data("size",size).data("memberId",memberId);
    }

    //文章

    //发表评论
    @PostMapping("saveComment/{vid}")
    @Transactional(rollbackFor = Exception.class)
    public ResultData saveComment(
            @PathVariable("vid") String vid,
            @RequestBody(required = false) String context,
            HttpServletRequest request){
        context=context.substring(1,context.length()-1);
        //从请求中获取token
        String token = JwtUtils.getMemberIdByJwtToken(request);
        if (StringUtil.isNullOrEmpty(token))
            throw new CustomException(20001,"请先登录");
        Comment comment =new Comment();
        EduVideo video = videoService.getById(vid);
        String memberId = JwtUtils.getMemberIdByJwtToken(request);
        Map<String, String> userInfo = client.getUserInfo(memberId);
        String snowflakeId = SnowflakeIdWorker.getSnowflakeId();
        comment.setId(snowflakeId);
        String courseId = video.getCourseId();
        comment.setCourseId(courseId);
        comment.setMemberId(memberId);
        comment.setContent(context);
        comment.setAvatar(userInfo.get("avatar"));
        comment.setNickname(userInfo.get("nickname"));
        comment.setGmtCreate(new Date());
//        commentService.save(comment);
        mongoTemplate.save(comment,"comment");
        courseService.update().eq("id",courseId).setSql("comment_count = comment_count+1").update();
        return ResultData.ok();
    }

    @DeleteMapping("delComment/{commentId}")
    public ResultData delComment(@PathVariable String commentId){
        try {
//        commentService.removeById(commentId);
            Query query =new Query(Criteria.where("id").is(commentId));
            Comment comment = mongoTemplate.findOne(query, Comment.class, "comment");
            String courseId = comment.getCourseId();
            mongoTemplate.remove(query,Comment.class,"comment");
            courseService.update().eq("id",courseId).setSql("comment_count = comment_count - 1").update();
        } catch (Exception e) {
            e.printStackTrace();
            return ResultData.error().message("删除失败");
        }
        return ResultData.ok();
    }

    @GetMapping("getViewCount")
    public Integer getViewCount(){
        String viewCount = redisTemplate.opsForValue().get("viewCount");
        //统计之后将数据初始化
        redisTemplate.opsForValue().set("viewCount","0");
        return Integer.parseInt(viewCount);
    }

    //浏览数+1的方法 同时到历史记录表中添加数据
    @GetMapping("viewCount/{vid}")
    public void viewCount(@PathVariable String vid,HttpServletRequest request){
        redisTemplate.opsForValue().increment("viewCount",1l);
        //更新对应课程的浏览数
        EduVideo video = videoService.getById(vid);
        String courseId = video.getCourseId();
        courseService.updateViewCount(courseId);
        //更新历史记录表
        //先拿到token中的用户信息，如果存在用户信息，则添加历史记录
        //获取用户id
        String memberId = JwtUtils.getMemberIdByJwtToken(request);
        if (!StringUtil.isNullOrEmpty(memberId)){
            //判断用户是否看的同一门课程，这个时候只需要更新小节id就可以了，避免同一课程历史记录重复
            QueryWrapper<History> wrapper =new QueryWrapper<>();
            wrapper.eq("course_id",courseId)
                    .eq("member_id",memberId);
            History one = historyService.getOne(wrapper);
            if (one!=null){
                //表示是同一个用户观看同一个课程，只需要更新小节id即可
                one.setVideoId(vid);
                historyService.updateById(one);
            }else {
                //表示不是同一个用户看同一个课程，那么需要做新增历史记录
                History history = new History();
                EduCourse course = courseService.getById(courseId);
                history.setVideoId(vid);
                history.setCourseId(courseId);
                history.setMemberId(memberId);
                history.setTitle(course.getTitle());
                historyService.save(history);
            }
        }
    }
}
